import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Logger;

public class Done implements Command {
	public ArrayList<Task> tasks;
	public AddParser addParser;
	public Storage storage;
	public History history;
	public Logger logger;
	private boolean isError = false;
	String data;
	String errorMessage;
	String output;

	private static final String DONE_SUCCESSFUL = "Task %d is set to done\n";
	private static final String INVALID_TASK_INDEX = "Task index is invalid\n";
	private static final String COMMAND_DONE = "done";
	private static final int BASEINDEX = 1;

	public Done(ArrayList<Task> tasks, Storage storage, History history,
			Logger logger) {
		this.tasks = tasks;
		this.addParser = new AddParser();
		this.storage = storage;
		this.history = history;
		this.logger = logger;
		errorMessage = "";
	}

	@Override
	public void acceptInput(String data) {
		// TODO Auto-generated method stub
		this.data = data;

	}

	@Override
	public void execute() {

		// TODO Auto-generated method stub
		int id;
		id = getTaskID(data);
		if (isIDValid(id)) {
			history.storeUndo(tasks, COMMAND_DONE);
			System.out.println(history.undoStack.peek().getTasks().get(0)
					.isDone());
			System.out.println(history.undoStack.size());
			tasks.get(id - BASEINDEX).setDone(true);
			output = String.format(DONE_SUCCESSFUL, id);
		} else {
			output = String.format(INVALID_TASK_INDEX);
			isError = true;
		}



	}

	@Override
	public String save() throws IOException {
		// TODO Auto-generated method stub
		return storage.writeToStorage(tasks);
	}

	@Override
	public String outputToUser() {
		// TODO Auto-generated method stub

		if (!errorMessage.equals("")) {
			output = errorMessage;
			isError = true;
		}

		return output;
	}

	// check if the original ID given by the user is valid. NOTE: ID is not
	// adjusted to base 0 of ArrayList
	private boolean isIDValid(int id) {

		if (tasks.size() >= 1) {
			if (id >= 1 && id <= tasks.size()) {
				return true;
			}
		}
		return false;
	}

	private int getTaskID(String data) {
		return Integer.valueOf(obtainFirstWord(data));
	}

	private String obtainFirstWord(String sentence) {

		String[] words;
		String trimmedSentence;
		trimmedSentence = sentence.trim();

		words = trimmedSentence.split(" ");

		return words[0];

	}

	@Override
	public boolean isError() {
		// TODO Auto-generated method stub
		return isError;
	}

}
